package src.java.medium;

import java.util.ArrayList;
import java.util.List;

public class Solution46 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> result = new Solution46().permute(nums);
    }

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        backtrack(result, new ArrayList<>(), nums, used);
        return result;
    }


    public void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, boolean[] used) {
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            tempList.add(nums[i]);
            used[i] = true;
            if (tempList.size() == nums.length) {
                result.add(new ArrayList<>(tempList));
                tempList.removeLast();
                used[i] = false;
                break;
            }
            backtrack(result, tempList, nums, used);
            tempList.removeLast();
            used[i] = false;
        }
    }
}
